import * as turf from '@turf/turf'
import GeoJSON from 'ol/format/GeoJSON'

/**
 * 判断点在线上
 * @param {*} point
 * @param {*} line
 */
export const booleanPointOnLine = (point, line) => {
  let turfPoint = feature2TurfFeature(point);
  let turfLine = feature2TurfFeature(line);
  return turf.booleanPointOnLine(turfPoint, turfLine);
}

/**
 * 缓冲区分析
 * @param {*} featureArr 缓冲要素集合
 * @param {*} bufferFeature 缓冲区
 */
export const buffer = (featureArr, bufferFeature) => {
  let returnArr = [];
  if (featureArr && featureArr instanceof Array && featureArr.length > 0 && bufferFeature) {
    let bufferTurfFeature = feature2TurfFeature(bufferFeature);
    if (bufferTurfFeature) {
      featureArr.forEach(feature => {
        let turfFeature = feature2TurfFeature(feature);
        //判断两个要素是否相离
        let boolDisjoint = turf.booleanDisjoint(bufferTurfFeature, turfFeature);
        //判断两个要素是否包含
        let boolContains = turf.booleanContains(bufferTurfFeature, turfFeature);
        if (!boolDisjoint || boolContains) {
          returnArr.push(feature)
        }
      });
    }
  }
  return returnArr
}

/**
 * 获取feature的坐标
 * @param {*} feature
 */
const getGeom = (feature) => {
  if (feature && feature.getGeometry()) {
    let length = feature.getGeometry().flatCoordinates.length
    let pointArr = feature.getGeometry().flatCoordinates
    let coor = []
    for (let index = 0; index < length; index += 2) {
      let flag = true
      coor.find(function (value) {
        if (value[0] === pointArr[index] && value[1] === pointArr[index + 1]) {
          flag = false
        }
      })
      if (flag) {
        coor.push([pointArr[index], pointArr[index + 1]])
      }
    }
    return coor.length === 1 ? JSON.stringify(coor[0]) : JSON.stringify(coor);
  }
  return "";
}

/**
 * 获取feature的类型
 * @param {*} feature
 */
const getType = (feature) => {
  if (feature && feature.getGeometry()) {
    return feature.getGeometry().getType();
  }
  return undefined;
}

/**
 * openLayers Feature 转 turf Feature
 * @param {*} feature
 */
const feature2TurfFeature = (feature) => {
  let type = getType(feature);
  switch (type) {
    case 'Point' :
      //语句
      return turf.point(JSON.parse(getGeom(feature)))
    //    break; //可选
    case 'LineString' :
      //语句
      return turf.lineString(JSON.parse(getGeom(feature)))
    //    break; //可选
    case 'Polygon' : {
      //语句
      let geom = JSON.parse(getGeom(feature));
      geom.push(geom[0])
      return turf.polygon([geom])
    }
    // break; //可选
    //你可以有任意数量的case语句
    default : //可选
      //语句
      return undefined
  }
}

const turfFeature2Feature = (turfFeature) => {
  return (new GeoJSON()).readFeature(turfFeature)
}
